package com.daichi.yygh.cmn.controller;

import com.daichi.yygh.cmn.service.DictService;
import com.daichi.yygh.common.result.Result;
import com.daichi.yygh.model.cmn.Dict;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Api(tags = "数据字典管理")
@RestController
@RequestMapping("/admin/cmn/dict")
public class DictController {
    private final DictService dictService;

    @Autowired
    public DictController(DictService dictService) {
        this.dictService = dictService;
    }

    @ApiOperation(value = "根据dictCode获取下级节点")
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    @GetMapping("findByDictCode/{dictCode}")
    public Result findByDictCode(@PathVariable String dictCode) {
        List<Dict> dictList = dictService.findByDictCode(dictCode);
        return Result.ok(dictList);
    }

    @ApiOperation(value = "根据id查询子数据")
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    @GetMapping("findChildData/{id}")
    public Result findChildrenData(@PathVariable Long id) {
        List<Dict> dictList = dictService.findChildrenData(id);
        return Result.ok(dictList);
    }

    @ApiOperation(value = "导出数据字典")
    @GetMapping("exportData")
    public void exportDict(HttpServletResponse response) {
        dictService.exportDictData(response);
    }

    @ApiOperation(value = "导入数据字典")
    @CacheEvict(value = "dict", allEntries = true)
    @PostMapping("importData")
    public Result importDict(MultipartFile file) {
        dictService.importDictData(file);
        return Result.ok();
    }

    @ApiOperation(value = "根据dictcode和value查询")
    @GetMapping("getName/{dictCode}/{value}")
    public String getName(@PathVariable String dictCode,
                          @PathVariable String value) {
        String dictName = dictService.getDictName(dictCode, value);
        return dictName;

    }

    @ApiOperation(value = "根据value查询")
    @GetMapping("getName/{value}")
    public String getName(@PathVariable String value) {
        String dictName = dictService.getDictName(null, value);
        return dictName;

    }

}
